package com.zb.http;

import com.alibaba.fastjson.JSON;
import org.springframework.http.*;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 请求工具类
 * @Author WEN
 * @Date 2024/2/29 0029
 **/
public class HttpClientUtil {
    private static final RestTemplate restTemplate = new RestTemplate();


    /**
     * 发送Post请求
     * @param url 请求路径
     */
    public static String post(String url) {
        return post(url, null, null);
    }


    /**
     * 发送Post请求
     * @param url 请求路径
     * @param paramMap 请求参数
     */
    public static String post(String url, Map<String, Object> paramMap) {
        return post(url, null, paramMap);
    }


    /**
     * 发送Post请求
     * @param url 请求路径
     * @param headerMap 请求头
     * @param paramMap 请求参数
     */
    public static String post(String url, Map<String, String> headerMap, Map<String, Object> paramMap) {
        // 请求请求头
        HttpHeaders headers = new HttpHeaders();
        if (null == headerMap) {
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        }
        if (null != headerMap &&headerMap.size() > 0) {
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                headers.add(entry.getKey(), entry.getValue());
            }
        }
        String body = null;
        if (null != paramMap && paramMap.size() > 0) {
            body = JSON.toJSONString(paramMap);
        }
        HttpEntity<String> entity = new HttpEntity<>(body, headers);
        String result = restTemplate.postForObject(url, entity, String.class);
        return result;
    }

    /**
     * 发送Put请求
     * @param url 请求路径
     * @param headerMap 请求头
     * @param paramMap 请求参数
     */
    public static String put(String url, Map<String, String> headerMap, Map<String, Object> paramMap) throws RestClientException {
        // 请求请求头
        HttpHeaders headers = new HttpHeaders();
        if (null == headerMap) {
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        }
        if (null != headerMap &&headerMap.size() > 0) {
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                headers.add(entry.getKey(), entry.getValue());
            }
        }
        String body = null;
        if (null != paramMap && paramMap.size() > 0) {
            body = JSON.toJSONString(paramMap);
        }
        HttpEntity<String> entity = new HttpEntity<>(body, headers);
        setMessageConverters();
        ResponseEntity<String> result = restTemplate.exchange(url, HttpMethod.PUT, entity, String.class);
        return result.getBody();
    }

    // 设置字符
    private static void setMessageConverters() {
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
    }
}
